﻿#include "tds.h"
#include "storage/StoragePreferences.h"
#include "utils/log.h"

#define CARTRIDGE_TDS1_KEY "cartridge_TDS1"
#define CARTRIDGE_TDS2_KEY "cartridge_TDS2"

namespace water {

static unsigned int UITDS1 = 1;              //TDS1
static unsigned int UITDS2 = 1;              //TDS2
const uint32_t POLAR_CONSTANT = 598000;

//TDS计算
int R_TDS_Calculate(uint16_t adc, uint16_t temperature) {
    int tds_Value;
    int tds_resister;
    float siemens_value = 0;//西门子值
    float electornic_conductor = 0;

    int adctemp = adc;
    int adc_avg_value = 4096 - adctemp;

    //获取温度值
    /*AD限值处理*/
    if(adc_avg_value >= 4070) { //998
       tds_Value = 0;
    } else {
      //计算溶液电阻值
      /* 1.5k的串联液体TDS电阻值 */
      tds_resister = (adc_avg_value * 1000) / (4096 - adc_avg_value);

      /* 计算电导率值 。 其中POLAR_CONSTANT 为电导池常数*/
      siemens_value = (1.0 * POLAR_CONSTANT / tds_resister);

      /* temperature adjust */
      //经过温度补偿过的电导率值
      electornic_conductor = siemens_value * (1 - 0.018 * (temperature - 25));

      // 计算出TDS值，TDS_COEFFICIENT为转换系数
      tds_Value = (uint16_t)(1.0 * electornic_conductor * TDS_COEFFICIENT / 100);
    }

    if(tds_Value <= 0) {
        tds_Value = 1;
    }

    return tds_Value;
}

void refresh_TDS_data(int tds1, int tds2, int ad) {
	UITDS1 = R_TDS_Calculate(tds1, ad);
	if (UITDS1 < 0) {
		UITDS1 = 1;
	}

	UITDS2 = R_TDS_Calculate(tds2, ad);
	if (UITDS2 < 0) {
		UITDS2 = 1;
	}

//	LOGD("yuan1:%d, yuan2:%d, temp:%d, tds1:%d, tds2:%d\n",tds1, tds2, ad, UITDS1, UITDS2);
}

unsigned int get_TDS1() {
    return UITDS1;
}
unsigned int get_TDS2() {
    return UITDS2;
}

void set_TDS1(int tds) {
    UITDS1 = tds;
}

void set_TDS2(int tds) {
    UITDS2 = tds;
}

int get_tds1() {
	return StoragePreferences::getInt(CARTRIDGE_TDS1_KEY, 1);
}

int get_tds2() {
	return StoragePreferences::getInt(CARTRIDGE_TDS2_KEY, 1);
}

void save_tds() {
    StoragePreferences::putInt(CARTRIDGE_TDS1_KEY, UITDS1);
	StoragePreferences::putInt(CARTRIDGE_TDS2_KEY, UITDS2);
}

void init_tds()
{
    set_TDS1(get_tds1() < 1? 1: get_tds1());
    set_TDS2(get_tds2() < 1? 1: get_tds2());
}

}
